<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>29 渲染大数据不卡页面</title>
	</head>

	<body>
		<button onclick="alert(1)">alert</button>
		<ul></ul>
		<!-- 渲染几万条数据不卡住页面 -->
		<script>
			// 渲染大数据时，合理使用 createDocumentFragment 和 requestAnimationFrame ，将操作切分为一小段一小段执行。
			setTimeout(() => {
				// 插入十万条数据
				let msg = 0;
				const total = 100000;
				// 一次插入的数据
				const once = 20;
				// 插入数据需要的次数
				const loopCount = Math.ceil(total / once);
				let countOfRender = 0;
				const ul = document.querySelector('ul');
				// 添加数据的方法
				function add() {
					const fragment = document.createDocumentFragment();
					for (let i = 0; i < once; i++) {
						msg += 1;
						const li = document.createElement('li');
						li.innerText = Math.floor(msg);
						fragment.appendChild(li);
					}
					ul.appendChild(fragment);
					countOfRender += 1;
					loop();
				}
				function loop() {
					if (countOfRender < loopCount) {
						window.requestAnimationFrame(add);
					}
				}
				loop();
			}, 0);
		</script>
	</body>
</html>
